import store from '../store/index.js'
const basicUrl = "https://gateway.xiaohong.work/api"
// const basicUrl = "http://47.93.213.92:9001/file/upload"
// const basicUrl = "http://127.0.0.1:9001"
// const basicUrl = "http://119.29.67.157:9004"
const imgsuffixList= ["jpg","jpeg","png","gif"]
const videosuffixList = ["mp4","avi","flv","mov","rm","rmvb"]
const musicsuffixList = ["mp3"]

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function renderSize(filesize){
   if(null==filesize||filesize==''){
       return "0 Bytes";
   }
   var unitArr = new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");
   var index=0;
   var srcsize = parseFloat(filesize);
   index=Math.floor(Math.log(srcsize)/Math.log(1024));
   var size =srcsize/Math.pow(1024,index);
   size=size.toFixed(2);//保留的小数位数
   return size+unitArr[index];
}

var dateFormat = function (timestamp, formats) {
    // formats格式包括
    // 1. Y-m-d
    // 2. Y-m-d H:i:s
    // 3. Y年m月d日
    // 4. Y年m月d日 H时i分
    formats = formats || 'Y-m-d';

    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    var myDate = timestamp? new Date(timestamp): new Date();

    var year = myDate.getFullYear();
    var month = zero(myDate.getMonth() + 1);
    var day = zero(myDate.getDate());

    var hour = zero(myDate.getHours());
    var minite = zero(myDate.getMinutes());
    var second = zero(myDate.getSeconds());

    return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
        return ({
            Y: year,
            m: month,
            d: day,
            H: hour,
            i: minite,
            s: second
        })[matches];
    });
};

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
}

// 将rpx转px
function sizeDeal (size) {
	const info = uni.getSystemInfoSync()
	let scale = 750 / info.windowWidth;
	// 分离字体大小和单位,rpx 转 px
	let s = Number.isNaN(parseFloat(size)) ? 0 : parseFloat(size)
	let u = size.toString().replace(/[0-9]/g, '').replace('-', '')
	if (u == 'rpx') {
		s /= scale
		u = 'px'
	} else if (u == '') {
		u = 'px'
	} else if (u == 'vw') {
		u = 'px'
		s = s / 100 * 750 / scale
	}
	return [s, u, s + u]
}

function sliceFile(file,fileSize){
	// plus.io.resolveLocalFileSystemURL(path, (entry) => {
	// 	entry.file((file) => {
	// 		FileSpliter.splitFile({
	// 			filePath: file.fullPath,  //选择文件的完整路径，例如"/storage/0/..."
	// 			savePath: savePath,  //保存文件的完整路径，需要该路径存在, 例如"/storage/0/..."
	// 			fileName: file.name, //"文件名"  
	// 			chunkSize: 1024 * 1024 * 1  //每一片的大小, 例如 1024 * 1024 * 10  代表10MB
	// 		}, (ret) => {
	// 			//成功的回调
	// 			if (ret) {
	// 				if (ret.code == 'process') {
	// 					console.log("name", ret.name); //分片的所属文件名，用于区分多文件同时切片
	// 					console.log("chunk", ret.chunk); //分片序号
	// 					console.log("path", ret.path);  //分片的绝对路径
	// 				} else if (ret.code == 'complete') {
	// 					console.log("切片完成");
	// 				} else if (ret.code == 'start') {
	// 					console.log("切片开始");
	// 				}
	// 			}
	// 		}, (ret) => {
	// 			//失败的回调
	// 		});

	// 	})
	// })
	var SLICE_SIZE = 1024*1024
	console.log("选定视频的大小"+fileSize )
	var blobList = []
	if (fileSize  > SLICE_SIZE){
		// 计算需要分几份
		let sliceCount = Math.ceil(fileSize / SLICE_SIZE);
		for (let i = 0; i < sliceCount; ++i) {
			// 计算分片起始位置
			let start = i * SLICE_SIZE;
			// 计算分片结束位置
			let end = start + SLICE_SIZE;
			// 最后一片特殊处理
			if (end > fileSize) {
				end = fileSize;
			}
			let newBlob = file.slice(start, end);
			blobList.push(newBlob)
			// balabala 业务代码
		}
		return blobList;
	}
}


// 请求失败错误处理中心
function requestFail (res) {
	// 令牌失效错误
	if(res.statusCode == 401){
		uni.showToast({
			icon:"none",
			title:"权限不足！"
		})
	}else if(res.statusCode == 404){
		uni.showToast({
			icon:"none",
			title:"未找到该服务请求！"
		})
	}else if(res.statusCode == 413){
		uni.showToast({
			icon:"none",
			title:"文件上传最大为1G"
		})
	}else if(res.statusCode == 500){
		uni.showToast({
			icon:"none",
			title:"后台错误！"
		})
	}else if(res.statusCode == 502){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else if(res.statusCode == 503){
		uni.showToast({
			icon:"none",
			title:"后台服务未启动！"
		})
	}else{
		uni.showToast({
			icon:"none",
			title:"其他错误，错误内容："+JSON.stringify(res)
		})
	}
	
}


module.exports = {
	formatTime,
	formatLocation,
	dateUtils,
	dateFormat,
	basicUrl,
	requestFail,
	renderSize,
	imgsuffixList,
	videosuffixList,
	musicsuffixList,
	sliceFile
}
